package main

import (
	"fmt"
	"math"
)

// 如何求解最小三元组距离

func main() {
	a := []int{3, 4, 7, 7, 15}
	b := []int{10, 12, 14, 16, 17}
	c := []int{20, 21, 23, 24, 37, 40}
	fmt.Println(minDistanceDyn(a, b, c))
}

func minDistanceDyn(a, b, c []int) int {
	aLen, bLen, cLen := len(a), len(b), len(c)
	minDistance := math.MaxInt64
	i, j, k := 0, 0, 0

	for true {
		currentDistance := max3(abs(a[i]-b[j]),
			abs(a[i]-c[k]), abs(b[j]-c[k]))
		if currentDistance < minDistance {
			minDistance = currentDistance
		}

		if a[i] < b[j] && a[i] < c[k] {
			i++
			if i == aLen {
				break
			}
		} else if b[j] < a[i] && b[j] < c[k] {
			j++
			if j == bLen {
				break
			}
		} else {
			k++
			if k == cLen {
				break
			}
		}
	}

	return minDistance
}

func abs(a int) int {
	if a < 0 {
		return -a
	}

	return a
}

func max3(a, b, c int) (max int) {
	if a < b {
		max = b
	} else {
		max = a
	}
	if c > max {
		max = c
	}

	return
}
